package com.design.twords.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.design.twords.MainActivity;
import com.design.twords.R;
import com.design.twords.config.ConfigData;
import com.design.twords.database.OcrWordsList;
import com.design.twords.database.Translation_all;
import com.design.twords.utils.ImageUtil;
import com.design.twords.utils.MediaHelper;
import com.design.twords.utils.MyApplication;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * Create by Alen
 * Time:  21:51
 */
public class WordPlayActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "WordPlayActivity";
    //暂停 取消按钮
    private Button bt_stop,bt_quit;
    //当前单词编号  总的单词数  单词含义  单词
    private TextView tv_wordnumber,tv_wordsum,word_means,word_name;
    //专辑图片
    private ImageView imageView;
    //单词卡片
    private RelativeLayout wordcard;
    //单词播放器
    private WordPlay wordPlay;

    //单词列表
    public ArrayList<String> words = new ArrayList<>();;

    //修改当前单词编号
    private static final int MSG_CHANGE_NUMBER = 1;
    //修改旋转状态
    private static final int MSG_CHANGE_STATE = 2;
    //资源获取失败
    private static final int MSG_FAIL_TO_GET = 3;
    //json解析出错
    private static final int JSON_WRONG = 4;


    //单词重复播放次数
    private static int WordPlay_Times = ConfigData.getRepeatTimes();
    //单词间延迟时间
    private static int WordPlay_DelayTime = ConfigData.getSpaceTime();
    //设置背景图
    private static boolean isShowTrans = ConfigData.isShowTrans();

    //动画效果
    private ObjectAnimator objectAnimator;
    //暂停标记 默认为False
    private volatile boolean isPause = false;
    //暂停位置标记
    private int IndexOfPause = 0;


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case MSG_CHANGE_NUMBER:
                    tv_wordnumber.setText(msg.arg1+"");
                    showWord();
                    break;
                case MSG_FAIL_TO_GET:
                    Toast.makeText(getApplicationContext(),"资源获取失败",Toast.LENGTH_LONG).show();
                    break;
                case JSON_WRONG:
                    Toast.makeText(getApplicationContext(),"出了一点小故障,请重试",Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wordplay);
        MyApplication.getInstance().addActivity(this);
        initView();
        initListener();

        //获取字符数组
        //words = getIntent().getStringExtra("wrods");
        Bundle bundle = getIntent().getBundleExtra("bundle");
        words =  bundle.getStringArrayList("words");
        tv_wordsum.setText("/"+words.size());

        //判定播放模式
        if (ConfigData.getPlaymode() == ConfigData.RANDOM_PLAY)
            Collections.shuffle(words);

        if (words.size() > 0){
            //开启单词播放器线程
            wordPlay = new WordPlay();
            wordPlay.start();
            //设置图片旋转动画
            Bitmap b = BitmapFactory.decodeResource(getResources(),R.drawable.img_wordplay);
            Bitmap bitmap = ImageUtil.createCircleImage(b);
            //background_image = FileUtil.saveBitmapFile(b);
            //Log.i("background_img:",background_image);
            imageView.setImageBitmap(bitmap);
            RotateImg();
        }else {
            Toast.makeText(this,"单词播放队列为空",Toast.LENGTH_LONG).show();
            onBackPressed();
        }


    }

    private void initListener() {
        bt_stop.setOnClickListener(this);
        bt_quit.setOnClickListener(this);
        imageView.setOnClickListener(this);
        wordcard.setOnClickListener(this);
    }

    //初始化
    private void initView() {
        bt_stop = findViewById(R.id.wordplay_bt_stop);
        bt_quit = findViewById(R.id.wordplay_bt_quit);
        tv_wordnumber = findViewById(R.id.wordplay_word_number);
        tv_wordsum = findViewById(R.id.wordplay_word_sum);
        imageView = findViewById(R.id.wordplay_img);
        wordcard = findViewById(R.id.wordplay_word_card);
        word_name = findViewById(R.id.wordplay_word);
        word_means = findViewById(R.id.wordplay_word_means);
        wordcard.setVisibility(View.GONE);
    }

    //单词播放器
    class WordPlay extends Thread{
        @Override
        public void run() {
            super.run();
            while(true){
                if(!isPause){
                    for (; IndexOfPause < words.size() && !isPause; IndexOfPause++) {
                        try {
                            //显示当前播放的单词
                            Log.d(TAG,"now word: "+ words.get(IndexOfPause));
                            //发送消息通知主线程 更新UI
                            Message message = new Message();
                            message.what = MSG_CHANGE_NUMBER;
                            message.arg1 = IndexOfPause + 1;
                            handler.sendMessage(message);
                            //循环播放
                            for (int j = 0; j < WordPlay_Times && !isPause; j++) {
                                //播放单词
                                MediaHelper.play(words.get(IndexOfPause));
                                //间隔时间
                                Thread.sleep(WordPlay_DelayTime * 1000);
                            }
                            Thread.sleep(2500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if(IndexOfPause >=words.size()) {
                    Intent intent = new Intent(WordPlayActivity.this, FinishActivity.class);
                    intent.putExtra("wordnumb",words.size());
                    startActivity(intent);
                    finish();
                    break;
                }
            }

        }
    }

    //图片旋转
    public void RotateImg(){
        objectAnimator = ObjectAnimator.ofFloat(imageView, "rotation", 0.0f, 360.0f);
        objectAnimator.setDuration(3000);
        // 无限循环
        objectAnimator.setRepeatCount(Animation.INFINITE);
        objectAnimator.setRepeatMode(ObjectAnimator.RESTART);
        // 匀速
        objectAnimator.setInterpolator(new LinearInterpolator());
        // 开始动画
        objectAnimator.start();
    }

    //点击事件
    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()){
            case R.id.wordplay_bt_stop:
                if(isPause){
                    //已经暂停  点击后继续播放
                    isPause = false;
                    objectAnimator.resume();
                    synchronized (wordPlay){
                        wordPlay.notifyAll();
                    }
                    bt_stop.setBackgroundResource(R.drawable.bt_drawable);
                    bt_stop.setText("暂停");
                }else{
                    //正在播放  点击后暂停
                    isPause = true;
                    objectAnimator.pause();
                    synchronized (wordPlay){
                        try {
                            wordPlay.interrupt();
                            MediaHelper.releasePlayer();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    bt_stop.setBackgroundResource(R.drawable.bt_onclicked_drawable);
                    bt_stop.setText("继续播放");
                }
                break;
            case R.id.wordplay_bt_quit:
                words.clear();
                MediaHelper.releasePlayer();
                wordPlay.interrupt();
                intent.setClass(WordPlayActivity.this, MainActivity.class);
                startActivity(intent);
                break;
            case R.id.wordplay_img:
                if (isShowTrans){
                    //图像切换
                    imageView.setVisibility(View.GONE);
                    wordcard.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.wordplay_word_card:
                if (isShowTrans){
                    //图像切换
                    imageView.setVisibility(View.VISIBLE);
                    wordcard.setVisibility(View.GONE);
                }
                break;
        }

    }

    public void showWord(){
        //找单词
        word_name.setText(words.get(IndexOfPause));
        //现在Ocr以前的记录中查找单词
        List<OcrWordsList> Ocrlists = LitePal.where("word = ?", words.get(IndexOfPause)).find(OcrWordsList.class);
        if(Ocrlists.size() > 0){
            for(int i = 0; i < Ocrlists.size(); i++){
                List<Translation_all> trans = LitePal.where("wordId = ? and wordBook = ?", Ocrlists.get(i).getWordId() +"", Ocrlists.get(i).getWordBook()).find(Translation_all.class);
                StringBuilder strbuilder = new StringBuilder();
                for(int j = 0; j < trans.size(); j++){
                    if (trans.get(j).getWordType() != null)
                        strbuilder.append(trans.get(j).getWordType()+": ");
                    strbuilder.append(trans.get(j).getCHSMeaning() + "\n");
                }
                word_means.setText(strbuilder.toString());
            }

        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().removeActivity(this);
    }
}
